<template>
  <div class="gantt-container">
    <!-- 头部控制区 -->
    <div class="gantt-header">
      <el-row :gutter="20" align="middle">
        <el-col :span="6">
          <h2>项目甘特图</h2>
        </el-col>
        <el-col :span="18" class="header-controls">
          <el-button type="primary" size="small" @click="zoomIn">
            <el-icon><zoom-in /></el-icon> 放大
          </el-button>
          <el-button type="primary" size="small" @click="zoomOut">
            <el-icon><zoom-out /></el-icon> 缩小
          </el-button>
          <el-button type="primary" size="small" @click="todayView">
            <el-icon><calendar /></el-icon> 今日
          </el-button>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="small"
            @change="handleDateRangeChange"
          />
        </el-col>
      </el-row>
    </div>
    <!-- 甘特图主体 -->
    <div class="gantt-wrapper">
      <!-- 任务列表区域 -->
      <div class="tasks-section">
        <el-table
          :data="tasks"
          border
          :height="ganttHeight"
          class="tasks-table"
        >
          <el-table-column prop="id" label="ID" width="60" />
          <el-table-column prop="name" label="任务名称" width="200" />
          <el-table-column
            prop="startDate"
            label="开始日期"
            width="120"
            :formatter="formatDateColumn"
          >
          </el-table-column>
          <el-table-column
            prop="endDate"
            label="结束日期"
            width="120"
            :formatter="formatDateColumn"
          />
          <el-table-column prop="progress" label="进度" width="140">
            <template #default="scope">
              <el-progress
                :percentage="scope.row.progress"
                stroke-width="6"
                :show-text="false"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 甘特图时间轴区域 -->
      <div class="timeline-section" :style="{ height: ganttHeight }">
        <div class="timeline-header" :style="{ width: timelineWidth }">
          <div
            v-for="(month, index) in displayedMonths"
            :key="index"
            class="timeline-month"
            :style="{ width: `${month.days * dayWidth}px` }"
          >
            {{ month.name }}
          </div>
        </div>

        <div class="timeline-days" :style="{ width: timelineWidth }">
          <div
            v-for="(day, index) in displayedDays"
            :key="index"
            class="timeline-day"
            :style="{ width: `${dayWidth}px` }"
            :class="{
              'day-weekend': isWeekend(day.date),
              'day-today': isToday(day.date),
            }"
          >
            <span class="day-number">{{ day.date.getDate() }}</span>
          </div>
        </div>

        <div
          class="tasks-bars"
          :style="{ width: timelineWidth, height: tasksHeight }"
        >
          <div
            v-for="(task, taskIndex) in tasks"
            :key="task.id"
            class="task-row"
            :style="{ height: `${rowHeight}px` }"
          >
            <div
              class="task-bar"
              :style="{
                left: `${getTaskLeftPosition(task)}px`,
                width: `${getTaskWidth(task)}px`,
                backgroundColor: task.color || getDefaultTaskColor(taskIndex),
                top: `${(rowHeight - 24) / 2}px`,
              }"
              @click="handleTaskClick(task)"
              :class="{ 'task-bar-overdue': isTaskOverdue(task) }"
            >
              <div class="task-bar-content">
                <span class="task-name">{{ task.name }}</span>
                <span class="task-progress">{{ task.progress }}%</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 任务详情弹窗 -->
    <el-dialog
      v-model="taskDetailVisible"
      :title="selectedTask ? selectedTask.name : '任务详情'"
      width="400px"
    >
      <template v-if="selectedTask">
        <el-descriptions column="1" border>
          <el-descriptions-item label="任务ID">{{
            selectedTask.id
          }}</el-descriptions-item>
          <el-descriptions-item label="开始日期">{{
            formatDate(selectedTask.startDate)
          }}</el-descriptions-item>
          <el-descriptions-item label="结束日期">{{
            formatDate(selectedTask.endDate)
          }}</el-descriptions-item>
          <el-descriptions-item label="进度">
            <el-progress :percentage="selectedTask.progress" stroke-width="6" />
          </el-descriptions-item>
          <el-descriptions-item label="负责人">{{
            selectedTask.assignee || "未分配"
          }}</el-descriptions-item>
          <el-descriptions-item label="备注">{{
            selectedTask.remark || "无"
          }}</el-descriptions-item>
        </el-descriptions>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { ZoomIn, ZoomOut, Calendar } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import moment from "moment";

const props = defineProps({
  tasks: {
    type: Array,
    required: true,
    default: () => [],
  },
  columns: {
    type: Array,
    required: true,
    default: () => [],
  },
  rowHeight: {
    type: Number,
    default: 40,
  },
});
const leftColumns = ref([]);

// 甘特图配置
const rowHeight = 60;
const defaultDayWidth = 40;
const ganttHeight = ref("600px");

// 缩放控制
const zoomLevel = ref(1);
const dayWidth = computed(() =>
  Math.max(20, defaultDayWidth * zoomLevel.value)
);

// 日期范围控制
const today = new Date();
const dateRange = ref([
  new Date(today.getFullYear(), today.getMonth() - 1, 1),
  new Date(today.getFullYear(), today.getMonth() + 2, 0),
]);

// 任务详情弹窗控制
const taskDetailVisible = ref(false);
const selectedTask = ref(null);

// 计算显示的日期范围
const displayedDays = computed(() => {
  const days = [];
  const start = new Date(dateRange.value[0]);
  const end = new Date(dateRange.value[1]);

  // 确保start是当天的开始时间
  start.setHours(0, 0, 0, 0);
  end.setHours(23, 59, 59, 999);

  let current = new Date(start);

  while (current <= end) {
    days.push({
      date: new Date(current),
      dayOfWeek: current.getDay(),
    });
    current.setDate(current.getDate() + 1);
  }

  return days;
});

// 计算显示的月份
const displayedMonths = computed(() => {
  const months = [];
  if (displayedDays.value.length === 0) return months;

  let currentMonth = displayedDays.value[0].date.getMonth();
  let currentYear = displayedDays.value[0].date.getFullYear();
  let daysInMonth = 0;

  displayedDays.value.forEach((day) => {
    if (
      day.date.getMonth() === currentMonth &&
      day.date.getFullYear() === currentYear
    ) {
      daysInMonth++;
    } else {
      months.push({
        name: `${currentYear}年${currentMonth + 1}月`,
        days: daysInMonth,
      });
      currentMonth = day.date.getMonth();
      currentYear = day.date.getFullYear();
      daysInMonth = 1;
    }
  });

  // 添加最后一个月
  months.push({
    name: `${currentYear}年${currentMonth + 1}月`,
    days: daysInMonth,
  });

  return months;
});

// 计算时间轴宽度
const timelineWidth = computed(() => {
  return `${displayedDays.value.length * dayWidth.value}px`;
});

// 计算任务区域高度
const tasksHeight = computed(() => {
  return `${props.tasks.length * rowHeight}px`;
});

// 检查是否为周末
const isWeekend = (date) => {
  const day = date.getDay();
  return day === 0 || day === 6;
};

// 检查是否为今天
const isToday = (date) => {
  return date.toDateString() === today.toDateString();
};

// 检查任务是否逾期
const isTaskOverdue = (task) => {
  return task.endDate < today && task.progress < 100;
};

// 获取任务条的起始位置
const getTaskLeftPosition = (task) => {
  const startDate = new Date(task.startDate);
  startDate.setHours(0, 0, 0, 0);

  // 找到任务开始日期在显示范围内的索引
  const startIndex = displayedDays.value.findIndex((day) => {
    return day.date.toDateString() === startDate.toDateString();
  });

  return startIndex >= 0 ? startIndex * dayWidth.value : 0;
};

// 获取任务条的宽度
const getTaskWidth = (task) => {
  const startDate = new Date(task.startDate);
  startDate.setHours(0, 0, 0, 0);
  const endDate = new Date(task.endDate);
  endDate.setHours(0, 0, 0, 0);

  // 计算任务的天数
  const dayDiff = Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24)) + 1;

  return dayDiff * dayWidth.value;
};

// 获取默认任务颜色
const getDefaultTaskColor = (index) => {
  const colors = [
    "#409eff",
    "#67c23a",
    "#e6a23c",
    "#f56c6c",
    "#909399",
    "#c0c4cc",
    "#722ed1",
    "#1890ff",
  ];
  return colors[index % colors.length];
};

// 格式化日期显示
const formatDate = (date) => {
  console.log(date);
  if (!date) return "";
  const d = new Date(date);
  return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, "0")}-${d.getDate().toString().padStart(2, "0")}`;
};
const formatDateColumn = (date) => {
  return date ? moment(date).format("YYYY-MM-DD") : "";
};

// 处理日期范围变化
const handleDateRangeChange = (newRange) => {
  if (newRange && newRange.length === 2) {
    dateRange.value = newRange;
  }
};

// 缩放控制方法
const zoomIn = () => {
  // if (zoomLevel.value < 2) {
  //   zoomLevel.value += 0.2;
  // } else {
  //   ElMessage.info("已达到最大缩放级别");
  // }
};

const zoomOut = () => {
  // if (zoomLevel.value > 0.5) {
  //   zoomLevel.value -= 0.2;
  // } else {
  //   ElMessage.info("已达到最小缩放级别");
  // }
};

// 查看今日视图
const todayView = () => {
  const start = new Date(today);
  start.setDate(today.getDate() - 7);

  const end = new Date(today);
  end.setDate(today.getDate() + 14);

  dateRange.value = [start, end];
  zoomLevel.value = 1;
};

// 处理任务点击
const handleTaskClick = (task) => {
  selectedTask.value = { ...task };
  taskDetailVisible.value = true;
};
watch(
  () => props.columns,
  (val) => {
    console.log(val, "val");
  }
);
// 组件挂载时初始化
// onMounted(() => {
//   // 可以在这里加载实际的任务数据
//   // const leftColumns = props.columns;
//   leftColumns.value = props.columns;
//   console.log(leftColumns.value, "leftColumns");
// });
</script>

<style scoped>
.gantt-container {
  width: 100%;
  padding: 16px;
  box-sizing: border-box;
}

.gantt-header {
  margin-bottom: 16px;
}

.header-controls {
  text-align: right;
}

.header-controls > * {
  margin-left: 8px;
}

.gantt-wrapper {
  display: flex;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  overflow: hidden;
}

.tasks-section {
  min-width: 540px;
  border-right: 1px solid #e5e7eb;
}

.tasks-table ::v-deep .el-table__row {
  height: 60px !important;
}

.timeline-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: auto;
  position: relative;
}

.timeline-header {
  display: flex;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e5e7eb;
  font-weight: bold;
  padding: 8px 0;
}

.timeline-month {
  text-align: center;
  padding: 4px;
  box-sizing: border-box;
  border-right: 1px solid #e5e7eb;
}

.timeline-days {
  display: flex;
  background-color: #f9fafb;
  border-bottom: 1px solid #e5e7eb;
}

.timeline-day {
  height: 30px;
  border-right: 1px solid #e5e7eb;
  box-sizing: border-box;
  position: relative;
}

.day-number {
  position: absolute;
  right: 2px;
  top: 2px;
  font-size: 12px;
  color: #666;
}

.day-weekend {
  background-color: #fef2f2;
}

.day-today {
  background-color: #fff7e6;
  font-weight: bold;
}

.day-today .day-number {
  color: #e6a23c;
}

.tasks-bars {
  position: relative;
  overflow: hidden;
}

.task-row {
  border-bottom: 1px solid #f0f0f0;
  position: relative;
}

.task-bar {
  position: absolute;
  height: 24px;
  border-radius: 4px;
  cursor: pointer;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.2s;
}

.task-bar:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.task-bar-overdue {
  background-color: #f56c6c !important;
  animation: blink 1.5s infinite;
}

@keyframes blink {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.7;
  }
  100% {
    opacity: 1;
  }
}

.task-bar-content {
  padding: 0 8px;
  color: white;
  font-size: 12px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 24px;
  display: flex;
  justify-content: space-between;
}

.task-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
}

.task-progress {
  margin-left: 8px;
  font-weight: bold;
  min-width: 30px;
  text-align: right;
}
</style>
